package com.lagou.client;

import com.lagou.util.JsonMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {


    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler;

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass, final String providerName) {
        //借助JDK动态代理生成代理对象
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法

                if (userClientHandler == null) {
                    initClient();
                }

                // 设置参数
//                userClientHandler.setPara(providerName+args[0]);
                userClientHandler.setEntiy((JsonMsg) args[0]);
                // 去服务端请求数据

                return executor.submit(userClientHandler).get();
            }
        });


    }


    //2.初始化netty客户端
    public static void initClient() throws Exception {
        userClientHandler = new UserClientHandler();

        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });

     /*   ClientComsumer clientComsumer = new ClientComsumer();
        String zk = clientComsumer.getServerinfo("zk");
        NodeStat nodeStat = JSONObject.parseObject(zk, NodeStat.class);
        bootstrap.connect(nodeStat.getIp(), Integer.valueOf(nodeStat.getPort())).sync();*/

        String discover = discover(FOLDER);
        String[] split = discover.split(":");
        System.out.println(split);
//        bootstrap.connect("127.0.0.1",8990).sync();
        bootstrap.connect(split[0],Integer.valueOf(split[1])).sync();


    }

    private   static CuratorFramework curatorFramework;
    protected static final String FOLDER = "/serverBootstrap";
    protected static final String SEPARATOR = "/";
    private static final int SESSION_TIMEOUT_MS = 5000;
    private static final int SLEEP_TIME_MS = 1000;
    private static final int MAX_RETRIES = 2;

    public  static void init() {
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(SESSION_TIMEOUT_MS)
                .retryPolicy(new ExponentialBackoffRetry(SLEEP_TIME_MS, MAX_RETRIES))
                .build();
        curatorFramework.start();
    }

    public  static String discover(String service) throws Exception {
        init();
        List<String> provider = curatorFramework.getChildren().forPath(service);
        return provider.get(0);
    }




}


